<template>
  <el-dialog
    class="dialog-box"
    v-model="dialogVisible"
    :title="!dialogParam.title ? '弹出框' : dialogParam.title"
    :destroy-on-close="true"
    width="800px"
    @close="handleCancel"
  >
    <div id="printTest" class="print-box">
      <div
        v-for="(orderItem, index) in listData"
        :key="index"
        class="sales-slip-box"
        v-loading="loading"
        style="
          font-family: inherit !important;
          -webkit-font-smoothing: antialiased;
          padding: 20px;
          page-break-after: always;
        "
      >
        <!-- 分页
          page-break-after: always;
           -->
        <div style="text-align: center">签购单</div>
        <div style="text-align: right; padding-bottom: 0.75rem">
          NO: {{ orderItem.contractOrderNumber }}
        </div>
        <div
          style="
            padding-top: 0.25rem;
            padding-bottom: 0.25rem;
            justify-content: space-between;
            display: flex;
          "
        >
          <div>服务单位:{{ orderItem.deptName }}</div>
          <div>日期:{{ orderItem.printDate }}</div>
          <div>销售人员:{{ orderItem.transactionName }}</div>
          <div>开票类型:{{ orderItem.invoiceTypeName }}</div>
        </div>
        <table border="1">
          <tbody>
            <tr>
              <td rowspan="3" style="width: 42px; text-align: center">
                顾客信息
              </td>
              <td style="text-align: center">顾客名称</td>
              <td>{{ orderItem.customerName }}</td>
              <td style="text-align: center">经办人</td>
              <td>{{ orderItem.cusLinkName }}</td>
              <td rowspan="3" style="width: 42px; text-align: center">
                交易方式
              </td>
              <td style="text-align: left"><span class="">☐</span>货款两清</td>
            </tr>
            <tr>
              <td style="text-align: center">
                <!-- 
                style="
                  text-align: justify;
                  text-align-last: justify;
                " -->
                税号
              </td>
              <td>{{ orderItem.customerCreditCode }}</td>
              <td style="text-align: center">固定电话</td>
              <td>{{ orderItem.linkPhone }}</td>
              <td class="text-left"><span class="">☐</span>先收款后发货</td>
            </tr>
            <tr>
              <td style="text-align: center">送货地址</td>
              <td>{{ orderItem.invoicePlace }}</td>
              <td style="text-align: center">移动电话</td>
              <td>{{ orderItem.linkPhone }}</td>
              <td><span class="">☐</span>先发货后收款</td>
            </tr>
          </tbody>
        </table>
        <table>
          <tbody>
            <tr>
              <td style="border-top: 0; width: 42px; text-align: center">
                序号
              </td>
              <td style="border-top: 0; text-align: center">商品名称规格</td>
              <td style="border-top: 0; text-align: center">单位</td>
              <td style="border-top: 0; text-align: center">数量</td>
              <td style="border-top: 0; text-align: center">含税单价</td>
              <td style="border-top: 0; text-align: center">含税金额</td>
              <td style="border-top: 0; text-align: center; max-width: 130px">
                备注
              </td>
              <td style="border-top: 0">顾客确认:</td>
            </tr>
            <tr v-for="(item, index) in orderItem.productInfoList" :key="index">
              <td style="text-align: center; width: 40px">{{ index + 1 }}</td>
              <td style="text-align: center">{{ item.name }}</td>
              <td style="text-align: center">{{ item.unit }}</td>
              <td style="text-align: center">{{ item.num }}</td>
              <td style="text-align: center">{{ item.actualPrice }}</td>
              <td style="text-align: center">{{ item.totalPrice }}</td>
              <td style="text-align: center">{{ item.remark }}</td>
              <td
                :rowspan="orderItem.productInfoList.length + 1"
                v-if="index == '0'"
                style="overflow-wrap: break-word; max-width: 130px"
              >
                <div>
                  注:本人已充分了解所购产品的功能、用途及服务等，是根据实际需要自愿选购的。
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="3" style="text-align: center">合计金额(大写)</td>
              <td colspan="4" style="text-align: center">
                <!-- {{ sumToChinese('28688.17') }} -->
                {{ orderItem.amountInWords }}
              </td>
            </tr>
          </tbody>
        </table>
        <div
          style="
            padding-top: 0.25rem;
            padding-bottom: 0.25rem;
            justify-content: space-between;
            display: flex;
          "
        >
          <div style="width: 25.8333333333%">收货人签字:</div>
          <div style="width: 22%">销售开单员:{{ orderItem.operator }}</div>
          <div style="width: 24%">财务审核:</div>
          <div style="width: 24%">库房管理员:</div>
          <div style="width: 4.1666666667%; text-align: right">
            {{ orderItem.printNumber }}
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <!-- <el-button type="primary" v-print="printObject" @click="handleAffirm">
          打印
        </el-button> -->
        <el-button type="primary" @click="printSpecificArea('printTest')">
          打印
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="SalesSlip">
import { getCurrentInstance, nextTick, watchEffect } from 'vue'

import { useDict } from '@/utils/dict'
import { strToArr } from '@/utils/commo'
import useCommonStore from '@/store/modules/common'

import { getSalesSlip, addSalesSlipNum } from '@/api/indentManage/indent'
const { proxy } = getCurrentInstance()

const { examine_frequency } = useDict('examine_frequency')

// 接受父级传递的参数
const props = defineProps({
  dialogParam: {
    required: true,
    type: Object || Array,
    default: () => {
      return {
        orderId: '',
        open: false
      }
    }
  }
})

// 弹出框是否隐藏
const dialogVisible = ref(false)
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 4
  },
  loading: false,
  listData: []
})
let { queryParams, loading, listData } = toRefs(data)

const printObject = reactive({
  id: 'printTest', // 这里是要打印元素的ID
  popTitle: '&nbsp', // 打印的标题
  extraCss: '', // 打印可引入外部的一个 css 文件
  extraHead: '', // 打印头部文字
  standard: 'strict',
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: '打印客户账单', // 打印预览的标题
  previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 10002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log('正在加载预览窗口！')
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log('已经加载完预览窗口，预览打开了！')
  }, // 预览窗口打开时的callback
  beforeOpenCallback() {
    console.log('开始打印之前！')
  }, // 开始打印之前的callback
  openCallback() {
    addNum()
    console.log('执行打印了！')
  }, // 调用打印时的callback
  closeCallback() {
    reset()
    console.log('关闭了打印工具！')
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log('点击v-print绑定的按钮了！')
  }
})
// 初始化
watch(
  () => props.dialogParam,
  async () => {
    dialogVisible.value = props.dialogParam.open // 表单弹出框
    queryParams.value = {
      ...queryParams.value,
      ...props.dialogParam.queryParam
    } // 查询参数
    getList()
  },
  {
    // flush: 'post'
    immediate: true,
    deep: true
  }
)

/* 增加打印次数 */
async function addNum() {
  let query = {
    orderIds: strToArr(props.dialogParam.queryParam.orderId)
  }
  let res = await addSalesSlipNum(query)
  if (res.code !== 200) return
  console.log(res, 'res')
}
/* 获取列表 */
async function getList() {
  let query = {
    orderIds: strToArr(props.dialogParam.queryParam.orderId)
  }
  loading.value = true
  let res = await getSalesSlip(query)
  loading.value = false
  if (res.code !== 200) return
  listData.value = res.data
  console.log(res, 'res')
}

// 确认操作
const handleAffirm = () => {}
function printSpecificArea(elementId) {
  let printableElement = document.getElementById(elementId)
  // let printStyle = window.getComputedStyle(printableElement, null)

  // console.log('样式printStyle==》', printStyle)
  // 创建一个新的隐藏iframe用于打印
  let iframe = document.createElement('iframe')
  iframe.style.display = 'none'
  document.body.appendChild(iframe)
  // 创建一个包含@page规则和背景颜色设置的style标签
  let printStyleContent = `
  @media print {
    @page {
      size: auto;
      margin: 3mm;
      font-family: inherit !important;
      -webkit-font-smoothing: antialiased;
      color: #000;
    }
  }
  .sales-slip-box {
    font-family: inherit !important;
    font-size: 14px;
    -webkit-font-smoothing: antialiased;
    padding: 20px;
  }
  .sales-slip-box table {
    width: 100%;
    font-size: 14px;
    border-collapse: collapse;
    }
  .sales-slip-box table td{
    border-width: 1px;
    --un-border-opacity: 1;
    border-color: rgba(0, 0, 0, 1);
    border-style: solid;
    padding: 0.3rem;
    box-sizing: border-box;
    }
  `
  // 创建style标签并写入内容
  let styleTag = document.createElement('style')
  styleTag.type = 'text/css'
  if (styleTag.styleSheet) {
    // 对于旧版IE浏览器
    styleTag.styleSheet.cssText = printStyleContent
  } else {
    // 其他现代浏览器
    styleTag.appendChild(document.createTextNode(printStyleContent))
  }
  // 将style标签添加到iframe的head部分
  iframe.contentDocument.head.appendChild(styleTag)
  // 将内联样式复制到iframe中
  // Array.from(document.styleSheets).forEach(function (styleSheet) {
  //   if (styleSheet.cssRules && styleSheet.ownerNode.nodeName !== 'STYLE') return
  //   let rules = styleSheet.cssRules || styleSheet.rules
  //   for (let i = 0; i < rules.length; i++) {
  //     let rule = rules[i]
  //     if (rule.type === CSSRule.STYLE_RULE) {
  //       let newStyleTag = document.createElement('style')
  //       newStyleTag.innerText = `${rule.selectorText} { ${rule.style.cssText} }`
  //       console.log('样式==》', newStyleTag)
  //       iframe.contentDocument.head.appendChild(newStyleTag)
  //     }
  //   }
  // })

  // 将需要打印的内容写入iframe的body
  iframe.contentDocument.body.innerHTML = printableElement.outerHTML
  // iframe.onload = function () {
  //   console.log('打印==》')
  // }
  // console.log('打印==》', iframe.onload)
  let iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow
  // 使用iframe的window对象调用print方法
  iframeWindow.print()
  // 在打印完成后，可以删除创建的iframe
  iframe.parentNode.removeChild(iframe)

  // 增加打印次数
  addNum()
}

// 取消操作
const handleCancel = () => {
  reset()
}
const reset = () => {
  dialogVisible.value = false
}

// function init() {
//   getList()
// }
// init()
</script>
<style lang="scss" scoped>
.dialog-box {
  .el-card {
    :deep(.el-card__body) {
      position: relative;
      overflow: hidden;
      padding: 0 !important;

      .suggest-tag {
        position: absolute;
        right: -30px;
        top: 10px;
        padding-left: 40px;
        padding-right: 40px;
      }
    }
  }
  .print-box {
    overflow: auto;
    max-height: 60vh;
  }
}
.sales-slip-box {
  font-family: inherit !important;
  -webkit-font-smoothing: antialiased;
  padding: 20px;
  table {
    @apply border-collapse w-full;
    td {
      @apply border-2 border-solid border-gray-300 p-2;
      box-sizing: border-box;
    }
  }
}
// 打印媒体查询
@media print {
  @page {
    size: auto;
    margin: 3mm;
    font-family: inherit !important;
    -webkit-font-smoothing: antialiased;
    color: #000;
  }
}
</style>
<style lang="scss">
.dialog-box {
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
}
</style>
